/*
 * Teknei 2014 - All rights reserved
 */
package com.teknei.acabus.core.controller.converter;

import java.util.List;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;

import org.primefaces.component.picklist.PickList;
import org.primefaces.model.DualListModel;

import com.teknei.acabus.core.entities.Role;

/**
 * Converter for faces utilities
 * @author Jorge Amaro
 * @version 1.0
 * @since 1.0
 *
 */
@FacesConverter("roleConverter")
public class RoleConverter implements Converter {

	/* (non-Javadoc)
	 * @see javax.faces.convert.Converter#getAsObject(javax.faces.context.FacesContext, javax.faces.component.UIComponent, java.lang.String)
	 */
	@Override
	public Object getAsObject(FacesContext context, UIComponent component,
			String value) {
		return getObjectFromUIPickListComponent(component, value);
	}

	/* (non-Javadoc)
	 * @see javax.faces.convert.Converter#getAsString(javax.faces.context.FacesContext, javax.faces.component.UIComponent, java.lang.Object)
	 */
	@Override
	public String getAsString(FacesContext context, UIComponent component,
			Object object) {
		String string;
		if (object == null) {
			string = "";
		} else {
			try {
				string = String.valueOf(((Role) object).getIdRole());
			} catch (ClassCastException cce) {
				throw new ConverterException();
			}
		}
		return string;
	}

	/**
	 * Finds the object based on its properties
	 * @param component
	 * @param value
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private Role getObjectFromUIPickListComponent(UIComponent component,
			String value) {
		final DualListModel<Role> dualList;
		try {
			dualList = (DualListModel<Role>) ((PickList) component).getValue();
			Role role = getObjectFromList(dualList.getSource(),
					Integer.valueOf(value));
			if (role == null) {
				role = getObjectFromList(dualList.getTarget(),
						Integer.valueOf(value));
			}

			return role;
		} catch (ClassCastException cce) {
			throw new ConverterException();
		} catch (NumberFormatException nfe) {
			throw new ConverterException();
		}
	}

	/**
	 * Finds the object based on its properties
	 * @param list
	 * @param identifier
	 * @return
	 */
	private Role getObjectFromList(final List<?> list, final Integer identifier) {
		for (final Object object : list) {
			final Role role = (Role) object;
			if (role.getIdRole().equals(identifier)) {
				return role;
			}
		}
		return null;
	}

}
